<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :span="24">
        <!-- <el-col :span="12">
          <el-form-item label="资源来源" prop="sourceFrom">
            <el-input v-model="formData.sourceName" placeholder="请输入资源来源" maxlength="30" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12"/> -->
        <el-col :span="12">
          <el-form-item label="资源名称" prop="sourceName">
            <el-input v-model="formData.sourceName" placeholder="请输入资源名称" maxlength="30" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资源编号" prop="sourceCode">
            <el-input v-model="formData.sourceCode" placeholder="请输入资源编号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资源类型" prop="sourceType">
            <el-select v-model="formData.sourceType" placeholder="请选择资源类型">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.SOURCE_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="来源信息" prop="sourceDesc">
            <el-select v-model="formData.sourceDesc" placeholder="请选择来源信息">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.SOURCE_DESC)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文件类型" prop="fileType">
            <el-select v-model="formData.fileType" placeholder="自动带出" disabled>
              <el-option
                v-for="dict in fileExtsList"
                :key="dict"
                :label="dict"
                :value="dict"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文件大小" prop="fileSize">
            <el-input v-model="formData.fileSize" placeholder="自动带出" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资源封面" prop="mainImage">
            <UploadImg
              v-model="formData.mainImage"
              :fileSize="200"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资源文件" prop="file">
            <UploadFile
              v-model="formData.file"
              :fileSize="2000"
              :limit="10"
              :fileType="fileExtsList"
              @change="onChangeFile"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, fileExtsList, DICT_TYPE } from '@/utils/dict'
import { SourceApi, SourceVO } from '@/api/dr/source'

/** 资源信息 表单 */
defineOptions({ name: 'SourceForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  sourceName: undefined,
  sourceCode: undefined,
  sourceType: undefined,
  sourceDesc: undefined,
  fileType: undefined,
  fileSize: undefined,
  mainImage: undefined,
  file: undefined,
  // 后台接口自己判断
  sourceFrom: '手工录入',
  sourceStatus: undefined,
})
const formRules = reactive({
  // sourceFrom: [
  //   { required: true, message: '请输入', trigger: ['blur', 'change'] },
  // ],
  sourceName: [
    { required: true, message: '请输入', trigger: ['blur', 'change'] },
  ],
  sourceCode: [
    { required: true, message: '请输入', trigger: ['blur', 'change'] },
  ],
  sourceType: [
    { required: true, message: '请选择', trigger: ['blur', 'change'] },
  ],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await SourceApi.getSource(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as SourceVO
    if (formType.value === 'create') {
      await SourceApi.createSource(data)
      message.success(t('common.createSuccess'))
    } else {
      await SourceApi.updateSource(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    sourceName: undefined,
    sourceCode: undefined,
    sourceType: undefined,
    sourceDesc: undefined,
    fileType: undefined,
    fileSize: undefined,
    mainImage: undefined,
    file: undefined,
    sourceFrom: '手工录入',
    sourceStatus: undefined,
  }
  formRef.value?.resetFields()
}
/** 选择文件 */
const onChangeFile = (files: any) => {
  console.log('onChangeFile', files)
  if (files && files.length > 0) {
    const file = files[0]
    formData.value.fileType = file.fileType
    formData.value.fileSize = file.size
  } else {
    formData.value.fileType = undefined
    formData.value.fileSize = undefined
  }
}
</script>
